import os
from core.logger import get_backend_logger

logger = get_backend_logger()

def current_file_directories():
    # 创建cache文件夹下的上传文件名文件夹
    current_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    return current_folder


def create_directories(novel_name):
    # 创建cache文件夹下的上传文件名文件夹
    project_root = current_file_directories()
    upload_dir = os.path.join(project_root, "cache", novel_name)
    os.makedirs(upload_dir, exist_ok=True)
    draft_folder, plot_folder, chapters_folder, split_folder =sub_folder_create(upload_dir, novel_name)
    return upload_dir, draft_folder, plot_folder, chapters_folder, split_folder

def sub_folder_create(upload_dir, novel_name):
    draft_folder = os.path.join(upload_dir, f"剧情摘要")
    plot_folder = os.path.join(upload_dir, f"章节大纲")
    chapters_folder = os.path.join(upload_dir, f"全文大纲")
    split_folder = os.path.join(upload_dir, f"拆解章节")
    if not os.path.exists(draft_folder):
        os.makedirs(draft_folder, exist_ok=True)
    if not os.path.exists(plot_folder):
        os.makedirs(plot_folder, exist_ok=True)
    if not os.path.exists(chapters_folder):
        os.makedirs(chapters_folder, exist_ok=True)
    if not os.path.exists(split_folder):
        os.makedirs(split_folder, exist_ok=True)

    return draft_folder, plot_folder, chapters_folder, split_folder

def check_existing_files(upload_dir, novel_name):
    draft_file = os.path.join(upload_dir, f"剧情摘要.txt")
    plot_file = os.path.join(upload_dir, f"章节大纲.txt")
    chapters_file = os.path.join(upload_dir, f"全文大纲.txt")
    
    file_check_msg = []
    if os.path.exists(draft_file):
        file_check_msg.append(f"剧情摘要文件 {draft_file} 已存在")
    if os.path.exists(plot_file):
        file_check_msg.append(f"章节大纲文件 {plot_file} 已存在")
    if os.path.exists(chapters_file):
        file_check_msg.append(f"全书大纲文件 {chapters_file} 已存在")
    
    return file_check_msg, draft_file, plot_file, chapters_file


def save_chapter_files(split_dir, chapter_titles, chapter_contents):
    # 按章节保存拆分后的文档
    for i, (title, content) in enumerate(zip(chapter_titles, chapter_contents), 1):
        chapter_file = os.path.join(split_dir, f"第{i}章_{title}_剧情摘要.txt")
        with open(chapter_file, 'w', encoding='utf-8') as f:
            chapter_name = ' '.join(title)
            f.write(f"{chapter_name}\n\n{content}")

def save_sole_draft_file(draft_file, chapter_name, content, i=None):
    # 修复文件路径构造问题，添加章节名作为文件名
    if i is not None:
        file_path = os.path.join(draft_file, f"第{i}章_{chapter_name}.txt")
    else:
        file_path = os.path.join(draft_file, f"{chapter_name}.txt")
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(f"{chapter_name}\n")
        f.write(content)
        f.write("\n\n")            
    return draft_file


def save_draft_file(draft_file, chapter_titles, dw_list):
    with open(draft_file, 'w', encoding='utf-8') as f:
        for i, (title, dw) in enumerate(zip(chapter_titles, dw_list), 1):
            chapter_name = ' '.join(title)
            f.write(f"## {chapter_name}\n")
            if hasattr(dw, 'x') and dw.x is not None:
                f.write(dw.x)
            else:
                logger.warning(f"第{i}章 {chapter_name} 剧情摘要内容为空或格式错误，跳过保存")
                f.write("剧情摘要内容为空或格式错误\n")
            f.write("\n\n")
    return draft_file


def save_plot_file(plot_file, chapter_titles, cw_list):
    with open(plot_file, 'w', encoding='utf-8') as f:
        for title, cw in zip(chapter_titles, cw_list):
            chapter_name = ' '.join(title)
            f.write(f"## {chapter_name}\n")
            if cw is not None:
                f.write(cw.global_context['chapter'])
            f.write("\n\n")
    return plot_file


def save_chapters_file(chapters_file, outline):
    with open(chapters_file, 'w', encoding='utf-8') as f:
        for title, content in outline.xy_pairs:
            f.write(f"## {title}\n")
            f.write(content)
            f.write("\n\n")
    return chapters_file